package com.hymns.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;

import org.xml.sax.SAXException;

import android.util.Xml;

import com.hymns.domain.Hymn;

public class XmlParser {

	private ArrayList<Hymn> _hymns;
	private static XmlParser _xmlParser;
	
	private XmlParser() {

	}

	public ArrayList<Hymn> getHymns(InputStream inputStream) throws IOException, SAXException {

		XmlSummHandler handler = new XmlSummHandler();

		Xml.parse(inputStream, Xml.Encoding.UTF_8, handler);

		_hymns = handler.GetHymns();
		
		Collections.sort(_hymns);

		return _hymns;
	}

	public Hymn getHymn(String fileName, InputStream inputStream) throws IOException, SAXException {
		
		for (Hymn item : _hymns) {
			if (item.get_File().equalsIgnoreCase(fileName)) {
				return  fillWithContent(item, inputStream);
			}
		}
		return null;
	}
	
	private Hymn fillWithContent(Hymn hymn, InputStream inputStream) throws IOException, SAXException{
		
		 XmlHymnHandler handler  = new XmlHymnHandler();

		Xml.parse(inputStream, Xml.Encoding.UTF_8, handler);

		Hymn tmpHymn= handler.GetHymn();
		
		hymn.set_Content(tmpHymn.get_Content());
		
		return hymn;
	}
	
	public static synchronized XmlParser getSingletonParser() {
		if (_xmlParser == null) {
			_xmlParser = new XmlParser();
		}
		return _xmlParser;
	}
}
